import React, { useState, useEffect } from 'react';
import { message, Drawer, Form, Input, Button, Row, Col, TreeSelect, Upload } from 'antd';
import { UploadOutlined, InboxOutlined } from '@ant-design/icons';
import local from '@/utils/local';
import { addField, upadataField } from '../api';
import styles from '../index.less';

const UpdateForm = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [fileList, setFileList] = useState([]); // 模板图片
  const [columnFileList, setColumnFileList] = useState([]); // 栏目模板图片
  const [articleFileList, setArticleFileList] = useState([]); // 文章模板图片

  // 详情
  const getDetailData = () => {
    const templateImgs = data.templateImg.split(',');
    const imgs = [];
    templateImgs.map((item, index) => {
      const imgNames = item.split('/');
      const imgName = imgNames[imgNames.length - 1];
      const obj = {
        uid: `tmp-${index}`,
        name: imgName,
        // eslint-disable-next-line no-undef
        url: `${baseUrl}${item}`,
        postUrl: item,
        status: 'done',
      };
      imgs.push(obj);
      return '';
    });
    setFileList(imgs);
    const articleFile = data.templateArticle || {};
    setArticleFileList([
      {
        uid: `templateArticle-0`,
        name: articleFile.fileName,
        // eslint-disable-next-line no-undef
        url: `${baseUrl}${articleFile.fileUrl}`,
        postUrl: articleFile.fileUrl,
        status: 'done',
      },
    ]);

    const columnFile = data.templateColumn || {};
    setColumnFileList([
      {
        uid: `ColumnFileList-0`,
        name: columnFile.fileName,
        url: `${baseUrl}${columnFile.fileUrl}`,
        postUrl: columnFile.fileUrl,
        status: 'done',
      },
    ]);

    form.setFieldsValue({ ...data });
  };

  useEffect(() => {
    setFileList([]);
    setColumnFileList([]);
    setArticleFileList([]);

    if (type === 'updata' && visible === true) {
      getDetailData();
    } else {
      form.resetFields();
    }
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  const accessToken = local.get('token');

  const coverImageProps = {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    showUploadList: true,
    listType: 'picture-card',
    fileList,
    data: { businessType: 'cms', fileName: 'fileName' },
    // eslint-disable-next-line no-undef
    action: `${API_PREFIX}/upload`,
    onChange: ({ fileList: newFileList }) => {
      setFileList(newFileList);
    },
    accept: 'image/gif,image/jpeg,image/png',
    multiple: 2,
    maxCount: 2,
  };

  const columnProps = {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    showUploadList: true,
    maxCount: 1,
    fileList: columnFileList,
    data: { businessType: 'cms', fileName: 'fileName' },
    // eslint-disable-next-line no-undef
    action: `${API_PREFIX}/upload`,
    onChange: info => {
      setColumnFileList(info.fileList);
    },
    // accept: 'text/html',
  };

  const articleProps = {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    showUploadList: true,
    maxCount: 1,
    fileList: articleFileList,
    data: { businessType: 'cms', fileName: 'fileName' },
    // eslint-disable-next-line no-undef
    action: `${API_PREFIX}/upload`,
    onChange: info => {
      setArticleFileList(info.fileList);
    },
    //  accept: '	text/html',
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = payload => {
    const hide = message.loading('正在添加');
    setLoading(true);
    upadataField({ ...payload, templateId: data.templateId }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   *
   * @param values
   */
  const addData = payload => {
    const hide = message.loading('正在添加');
    setLoading(true);
    addField({ ...payload }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '添加失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      const templateImg = [];
      const st = {
        templateImg: 1,
      };

      fileList.map(item => {
        const obj = {};
        if (
          (item.response && item.response.data && item.response.data.fileUrl) ||
          item.status === 'done'
        ) {
          obj.fileName = item.name;
          obj.fileUrl = item.postUrl ? item.postUrl : item.response.data.fileUrl;
          templateImg.push(obj);
        } else {
          st.templateImg = 0;
        }
        return '';
      });

      const articleTemplate = {};
      articleTemplate.fileName =
        articleFileList[0]?.response?.data?.fileName || articleFileList[0]?.name || '';
      articleTemplate.fileUrl =
        articleFileList[0]?.response?.data?.fileUrl || articleFileList[0]?.postUrl || '';

      const columnTemplate = {};
      columnTemplate.fileName =
        columnFileList[0]?.response?.data?.fileName || columnFileList[0]?.name || '';
      columnTemplate.fileUrl =
        columnFileList[0]?.response?.data?.fileUrl || columnFileList[0]?.postUrl || '';

      if (!columnTemplate.fileName || !articleTemplate.fileName) {
        message.error('请上传模板文件');
        return;
      }
      if (!templateImg || templateImg.length === 0) {
        message.error('请上传模板图片');
        return;
      }
      if (!st.templateImg) {
        message.error('模板图片上传失败，请重新上传');
        return;
      }
      const payload = {
        templateName: values.templateName,
        templateImg,
        articleTemplate,
        columnTemplate,
      };

      if (type === 'updata') updataData(payload);
      if (type === 'add') addData(payload);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  return (
    <>
      <Drawer
        getContainer={false}
        width={640}
        title={type === 'updata' ? '修改' : '添加'}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button onClick={sendData} type="primary" loading={loading} disabled={loading}>
              保存
            </Button>
          </div>
        }
      >
        <Form {...formItemLayout} name="control-ref" form={form}>
          <Form.Item label="模板名称" name="templateName" rules={[{ required: true }]}>
            <Input maxLength={20} allowClear />
          </Form.Item>
          <div className="g-labelStyle">
            <Form.Item label="栏目模板">
              <Form.Item name="columnFile">
                <Upload name="file" {...columnProps}>
                  <Button icon={<UploadOutlined />}>上传栏目模板</Button>
                </Upload>
                <span className={styles.tip}>模板只能上传一个(.html)，多次上传会覆盖</span>
              </Form.Item>
            </Form.Item>
            <Form.Item label="文章模板" rules={[{ required: true }]}>
              <Form.Item name="articleFile">
                <Upload name="file" {...articleProps}>
                  <Button icon={<UploadOutlined />}>文章模板</Button>
                </Upload>
                <span className={styles.tip}>模板只能上传一个(.html)，多次上传会覆盖</span>
              </Form.Item>
            </Form.Item>
            <Form.Item label="模板图片">
              <Form.Item name="img" noStyle>
                <Upload name="file" {...coverImageProps}>
                  {fileList.length < 2 && (
                    <>
                      上传<p style={{ fontSize: 12 }}>(最多2个)</p>
                    </>
                  )}
                </Upload>
              </Form.Item>
            </Form.Item>
          </div>
        </Form>
      </Drawer>
    </>
  );
};

export default UpdateForm;
